package com.sdp.irrigation.excel.field;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.redis.RedisUtil;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.irrigation.db.irrigation_eq.service.IIrrigationEqService;
import com.sdp.irrigation.db.irrigation_eq_real_time.service.IIrrigationEqRealTimeService;
import com.sdp.irrigation.entity.IrrigationEq;
import com.sdp.irrigation.entity.IrrigationEqRealTime;
import com.sdp.irrigation.entity.IrrigationEqType;
import com.sdp.irrigation.utils.GPSUtil;
import com.sdp.irrigation.utils.IrrigationConstants;
import com.sdp.right.entity.SysImportTemplateDetail;
import com.sdp.right.excel.importExcel.ImportExcelCallbackService;
import com.sdp.right.excel.importExcel.ImportExcelRowCallbackService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

@Service
public class EqExcelCallback implements ImportExcelCallbackService, ImportExcelRowCallbackService {

	private final ThreadLocal<Set<String>> threadLocal = ThreadLocal.withInitial(HashSet<String>::new);
	
	@Autowired
	private IIrrigationEqService eqService;
	
	@Autowired 
	private IIrrigationEqRealTimeService eqRealTimeService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public <T> void execute(T rowData, List<T> insertList, List<T> updateList,
			List<SysImportTemplateDetail> templateDetailList, AnalysisContext context) {
		IrrigationEq eq = (IrrigationEq) rowData;
		
		Set<String> eqNoSet = threadLocal.get();
		eqNoSet.add(eq.getEqNo());
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> void executeBatch(List<T> rowDataList, List<T> insertList, List<T> updateList,
			List<SysImportTemplateDetail> templateDetailList, AnalysisContext context) {
		CopyOptions options = CopyOptions.create()
                .setIgnoreNullValue(true);
		Set<String> eqNoSet = threadLocal.get();
		List<IrrigationEqType> eqTypeList = redisUtil.getCache(IrrigationEqType.class.getName());
		Map<String, IrrigationEqType> eqTypeMap = new ConcurrentHashMap<>();
		for (IrrigationEqType irrigationEqType : eqTypeList) {
			eqTypeMap.put(irrigationEqType.getTypeCode(), irrigationEqType);
		}
		
		QueryWrapper<IrrigationEq> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().in(IrrigationEq::getEqNo, eqNoSet);
		List<IrrigationEq> eqList = eqService.list(queryWrapper);
		Map<String, IrrigationEq> eqMap = new HashMap<>();
		for (IrrigationEq eq : eqList) {
			eqMap.put(eq.getEqNo(), eq);
		}
		
		List<IrrigationEqRealTime> eqRealTimeList = new ArrayList<>();
		for (Object obj : rowDataList) {
			IrrigationEq row = (IrrigationEq) obj;
			//设置图片
			if (!StringUtils.isEmpty(row.getEqType()) && eqTypeMap.containsKey(row.getEqType()) 
				&& !StringUtils.isEmpty(eqTypeMap.get(row.getEqType()).getImgUrl())) {
				row.setEqCoverimg(eqTypeMap.get(row.getEqType()).getImgUrl());
			}
			//设置经纬度
			if (!StringUtils.isEmpty(row.getGpsLongitude()) && !StringUtils.isEmpty(row.getGpsLatitude())) {
				double[] gps84_To_GD = GPSUtil.gps84_To_Gcj02(Double.parseDouble(row.getGpsLatitude()), Double.parseDouble(row.getGpsLongitude()));
				row.setMapLatitude(String.format("%.6f", gps84_To_GD[0]));
				row.setMapLongitude(String.format("%.6f", gps84_To_GD[1]));
			}
			if (eqMap.containsKey(row.getEqNo())) {
				BeanUtil.copyProperties(row, eqMap.get(row.getEqNo()), options);
				updateList.add((T) eqMap.get(row.getEqNo()));
				
			} else {
				row.setCreateTime(LocalDateTime.now());
				row.setUpdateTime(row.getCreateTime());
				row.setEqUseState(IrrigationConstants.否.getCode());
				row.setEqRepairStatus(IrrigationConstants.否.getCode());
				IrrigationEqRealTime eqRealTime = new IrrigationEqRealTime();
				eqRealTime.setEqNo(row.getEqNo());
				BeanUtils.copyProperties(row, eqRealTime);
				eqRealTimeList.add(eqRealTime);
				insertList.add((T)row);
			}
		}
		if (eqRealTimeList.size() > 0) {
			eqRealTimeService.saveBatch(eqRealTimeList);
		}
		
		//清理
		eqRealTimeList.clear();
		eqRealTimeList = null;
		eqList.clear();
		eqList = null;
		eqMap.clear();
		eqMap = null;
		eqNoSet.clear();
		
	}

	@Override
	public BusinessContext execute(HttpServletRequest request, HttpServletResponse response) {
		return null;
	}

}
